package priv.lhy.ecm.basic.init;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import priv.lhy.common.utils.JsonUtil;
import priv.lhy.ecm.basic.entity.dict.Dictionaryinfo;
import priv.lhy.ecm.basic.entity.dict.Dictionarytype;
import priv.lhy.ecm.basic.service.dict.DictionaryinfoServiceImpl;
import priv.lhy.ecm.basic.util.RedisUtil;

import java.util.List;
import java.util.Map;

/**
 * author: lihy
 * date: 2019/4/12 11:35
 * description: 初始化时将字典信息写入到redis
 */
@Component
@Order(value = 2)
public class DictInit implements CommandLineRunner {

    @Autowired
    private DictionaryinfoServiceImpl server;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${redis.data.index.dict}")
    private int dataIndex;

    @Override
    public void run(String... args) throws Exception {
        //切换数据库
        redisTemplate = RedisUtil.switchDatabase(redisTemplate,3);

        //将字典信息以hash方式全部保存到redis
        List<Dictionaryinfo> dictList = server.getAllDict();
        for (Dictionaryinfo info : dictList) {
            redisTemplate.opsForHash().put("DICTALL", info.getDid()+"", info.getDname());
        }

        //将字典信息按类型保存到redis
        Map<Dictionarytype, List<Dictionaryinfo>> map = server.getInitDict();
        for (Dictionarytype type : map.keySet()) {
            List<Dictionaryinfo> infos = map.get(type);
            redisTemplate.opsForValue().set("DICT:" + type.getDtid(), JsonUtil
                    .Object2Json(infos));
        }

    }
}
